package com.itheima.commons.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.Properties;

public class SendSMSUtil {
    //LTAI5tPboVgo9w1w2zxtnehW
    //0zA7a3k8ivlAbxbpCSCnYRyAohHCLU
    private static String access_key_id;
    private static String access_key_secret;
    private SendSMSUtil() {
    }

    static {
        Properties properties = new Properties();
        try {
            properties.load(SendSMSUtil.class.getClassLoader().getResourceAsStream("aliyun.properties"));
            access_key_id =properties.getProperty("sms.access_key_id");
            access_key_secret =properties.getProperty("sms.access_key_secret");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Boolean sendSMS(String phoneNum,String code,String codeTemple){

        DefaultProfile profile = DefaultProfile.getProfile("cn-qingdao", access_key_id, access_key_secret);
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("SignName", "杭州黑马传智健康");
        request.putQueryParameter("TemplateCode",codeTemple );
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            if (response.getData().contains("OK")) {
                return true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
